﻿using Aspose.Cells;
using Aspose.Cells.Rendering;
using WeighingRecord.Models;
using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;

namespace WeighingRecord.Services
{
    public class PrintHelper
    {
        private static Worksheet m_worksheet;
        private static Bitmap printBitmap;

        //打印过磅单图片
        public static void PrintImg(WeighingRecordModel record, Worksheet worksheet)
        {
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(@"衡七管家.exe");
            var appSection = (AppSettingsSection)cfg.GetSection("appSettings");

            string strPageWidth = appSection.Settings["PageSizeWidth"].Value;
            string strPageHeight = appSection.Settings["PageSizeHeight"].Value;
            int iWidth = Convert.ToInt32(strPageWidth) * 1000 / 254;
            int iHeight = Convert.ToInt32(strPageHeight) * 1000 / 254;

            Worksheet ws = new Workbook().Worksheets[0];
            ws.Copy(worksheet);

            m_worksheet = ws;

            #region 替换模板中的参数
            //设置替换区域：有内容的区域
            var range = m_worksheet.Cells.MaxDisplayRange;
            string cellRange = range.RefersTo.Split('!')[1].Replace("$", "");
            string startCellName = cellRange.Split(':')[0];
            string endCellName = cellRange.Split(':')[1];
            CellArea area = CellArea.CreateCellArea(startCellName, endCellName);
            //替换规则
            FindOptions opts = new FindOptions();
            opts.LookInType = LookInType.Values;
            opts.LookAtType = LookAtType.EntireContent;
            opts.SetRange(area);

            //逐个替换
            m_worksheet.Replace("_bh", record.Bh);
            m_worksheet.Replace("_kh", record.Kh);
            m_worksheet.Replace("_kh2", record.Kh2);
            m_worksheet.Replace("_kh3", record.Kh3);
            m_worksheet.Replace("_ch", record.Ch);

            m_worksheet.Replace("_mzsby", record.Mzsby);
            m_worksheet.Replace("_pzsby", record.Pzsby);
            m_worksheet.Replace("_goodsSpec", record.GoodsSpec);
            m_worksheet.Replace("_fhdw", record.Fhdw);

            DateTime temp = DateTime.Now;
            string Mzrq = record.Mzrq;
            if (!String.IsNullOrWhiteSpace(record.Mzrq) && DateTime.TryParse(record.Mzrq, out temp))
            {
                string formart = Common.Utility.SettingsHelper.AWSV2Settings.Settings["Mzrqgs"].Value;
                Mzrq = temp.ToString(formart);
                //Mzrq = temp.ToString("yyyy年MM月dd日 HH:mm:ss");
            }
            m_worksheet.Replace("_mzrq", Mzrq);


            string Pzrq = record.Pzrq;
            if (!String.IsNullOrWhiteSpace(record.Pzrq) && DateTime.TryParse(record.Pzrq, out temp))
            {
                string formart = Common.Utility.SettingsHelper.AWSV2Settings.Settings["Pzrqgs"].Value;
                Pzrq = temp.ToString(formart);
                //Pzrq = temp.ToString("yyyy年MM月dd日 HH:mm:ss");
            }
            m_worksheet.Replace("_pzrq", Pzrq);


            string Jzrq = record.Jzrq;
            if (!String.IsNullOrWhiteSpace(record.Jzrq) && DateTime.TryParse(record.Jzrq, out temp))
            {
                string formart = Common.Utility.SettingsHelper.AWSV2Settings.Settings["Jzrqgs"].Value;
                //Jzrq = temp.ToString("HH:mm:ss");
                //Jzrq = temp.ToString("yyyy年MM月dd日 HH:mm:ss");
                Jzrq = temp.ToString(formart);
            }
            m_worksheet.Replace("_jzrq", Jzrq);

            string dyrq = record.Dyrq;
            if (!String.IsNullOrWhiteSpace(record.Dyrq) && DateTime.TryParse(record.Dyrq, out temp))
            {
                string formart = Common.Utility.SettingsHelper.AWSV2Settings.Settings["Dyrqgs"].Value;
                dyrq = temp.ToString(formart);
            }
            m_worksheet.Replace("_dyrq", dyrq);
            m_worksheet.Replace("_jz", record.Jz);
            m_worksheet.Replace("_kz", record.Kz);
            m_worksheet.Replace("_kl", record.Kl);
            m_worksheet.Replace("_sz", record.Sz);
            m_worksheet.Replace("_bz", record.Bz);
            m_worksheet.Replace("_by1", record.By1);
            m_worksheet.Replace("_by2", record.By2);
            m_worksheet.Replace("_by3", record.By3);
            m_worksheet.Replace("_by4", record.By4);
            m_worksheet.Replace("_by5", record.By5);
            m_worksheet.Replace("_by6", record.By6);
            m_worksheet.Replace("_by7", record.By7);
            m_worksheet.Replace("_by8", record.By8);
            m_worksheet.Replace("_by9", record.By9);
            m_worksheet.Replace("_by10", record.By10);
            m_worksheet.Replace("_by11", record.By11);
            m_worksheet.Replace("_by12", record.By12);
            m_worksheet.Replace("_by13", record.By13);
            m_worksheet.Replace("_by14", record.By14);
            m_worksheet.Replace("_by15", record.By15);
            m_worksheet.Replace("_by16", record.By16);
            m_worksheet.Replace("_by17", record.By17);
            m_worksheet.Replace("_by18", record.By18);
            m_worksheet.Replace("_by19", record.By19);
            m_worksheet.Replace("_by20", record.By20);
            m_worksheet.Replace("_weighName", record.WeighName);
            m_worksheet.Replace("_weigh2Name", record.Weigh2Name);

            m_worksheet.Replace("_gblx", record.Gblx);
            m_worksheet.Replace("_je", record.Je);
            m_worksheet.Replace("_dj", record.GoodsPrice.ToString());
            m_worksheet.Replace("_axleNum", record.AxleNum);
            m_worksheet.Replace("_amount", record.Amount + "");
            m_worksheet.Replace("_credit", record.Credit + "");
            m_worksheet.Replace("_weigh", record.Weigh + "");
            m_worksheet.Replace("_weigh", record.Weigh + "");

            m_worksheet.Replace("_wz", record.Wz);
            m_worksheet.Replace("_mz", record.Mz);
            m_worksheet.Replace("_pz", record.Pz);
            m_worksheet.Replace("_jz", record.Jz);

            //2022-11-03新增打印字段
            m_worksheet.Replace("_driver", record.Driver);
            m_worksheet.Replace("_driverPhone", record.DriverPhone);
            m_worksheet.Replace("_entryTime", record.EntryTime.HasValue ? record.EntryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty);
            m_worksheet.Replace("_zflsh", record.Zflsh);
            m_worksheet.Replace("_zfje", record.Zfje.ToString());
            m_worksheet.Replace("_zfsj", record.Zfsj.HasValue ? record.Zfsj.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty);
            m_worksheet.Replace("_limitType", record.LimitType);
            m_worksheet.Replace("_limitedValue", record.LimitedValue);
            m_worksheet.Replace("_serialNumber", record.SerialNumber);

            m_worksheet.Replace("_isLimit", record.IsLimit ? "是" : "否");
            m_worksheet.Replace("_isCover", record.IsCover.GetValueOrDefault() ? "是" : "否");
            m_worksheet.Replace("_iccard", record.ICCard);
            m_worksheet.Replace("_isPay", record.IsPay == 1 ? "电子支付" : record.IsPay == 2 ? "线下支付" : record.IsPay == 3 ? "储值支付" : record.IsPay == 4 ? "免费放行" : "未支付");

            //新增打印此车当日总车次总毛净重
            Cell cell = null;
            cell = ws.Cells.Find("{weighcount}", cell, opts);
            if (cell != null)
            {
                string date = System.DateTime.Now.ToString("yyyy-MM-dd");
                var list = SQLDataAccess.LoadWeighingRecordCount(record.Ch, date);
                decimal mzcount = 0;
                decimal jzcount = 0;
                foreach (var item in list)
                {
                    mzcount += Convert.ToDecimal(item.Mz);
                    jzcount += Convert.ToDecimal(item.Jz);
                }
                cell.Value = $"{date}:车号{record.Ch},总车次{list.Count},总毛重{mzcount},总净重{jzcount}"; ;
            }
            #endregion

            //使用aspose插件将excel转换为图片
            printBitmap = ExcelToBmp(m_worksheet);

            try
            {
                //从数据库中读取配置的自定义纸张大小
                PrintDocument pd = new PrintDocument();
                PaperSize ps = new PaperSize("自定义", iWidth, iHeight);
                pd.DefaultPageSettings.PaperSize = ps;

                pd.PrintPage += new PrintPageEventHandler(Pd_PrintPage);

                //PrintPreviewDialog ppd = new PrintPreviewDialog();
                //ppd.WindowState = FormWindowState.Maximized;
                //ppd.Document = pd;
                //ppd.ShowDialog();                
                if (appSection.Settings["PrintingMode"].Value.Equals("Priview"))
                {
                    PrintPreviewDialog ppd = new PrintPreviewDialog();
                    ppd.WindowState = FormWindowState.Maximized;
                    ppd.Document = pd;
                    ppd.ShowDialog();
                }
                else
                {
                    string[] pList = appSection.Settings["Printer"].Value.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var p in pList)
                    {
                        pd.PrinterSettings.PrinterName = p;
                        pd.Print();
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        //打印过磅单图片
        public static void PrintImg1(WeighingRecordModel record, Worksheet worksheet)
        {
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(@"衡七管家.exe");
            var appSection = (AppSettingsSection)cfg.GetSection("appSettings");

            string strPageWidth = appSection.Settings["PageSizeWidth"].Value;
            string strPageHeight = appSection.Settings["PageSizeHeight"].Value;
            int iWidth = Convert.ToInt32(strPageWidth) * 1000 / 254;
            int iHeight = Convert.ToInt32(strPageHeight) * 1000 / 254;

            Worksheet ws = new Workbook().Worksheets[0];
            ws.Copy(worksheet);

            m_worksheet = ws;

            #region 替换模板中的参数
            //设置替换区域：有内容的区域
            var range = m_worksheet.Cells.MaxDisplayRange;
            string cellRange = range.RefersTo.Split('!')[1].Replace("$", "");
            string startCellName = cellRange.Split(':')[0];
            string endCellName = cellRange.Split(':')[1];
            CellArea area = CellArea.CreateCellArea(startCellName, endCellName);
            //替换规则
            FindOptions opts = new FindOptions();
            opts.LookInType = LookInType.Values;
            opts.LookAtType = LookAtType.EntireContent;
            opts.SetRange(area);
            //逐个替换
            Cell cell = null;
            cell = m_worksheet.Cells.Find("_bh", cell, opts);
            cell?.PutValue(record.Bh);

            cell = null;
            cell = m_worksheet.Cells.Find("_kh", cell, opts);
            cell?.PutValue(record.Kh);

            cell = null;
            cell = m_worksheet.Cells.Find("_kh2", cell, opts);
            cell?.PutValue(record.Kh2);

            cell = null;
            cell = m_worksheet.Cells.Find("_kh3", cell, opts);
            cell?.PutValue(record.Kh3);

            cell = null;
            cell = m_worksheet.Cells.Find("_ch", cell, opts);
            cell?.PutValue(record.Ch);

            cell = null;
            cell = m_worksheet.Cells.Find("_wz", cell, opts);
            cell?.PutValue(record.Wz);

            cell = null;
            cell = m_worksheet.Cells.Find("_mz", cell, opts);
            cell?.PutValue(record.Mz);

            cell = null;
            cell = m_worksheet.Cells.Find("_pz", cell, opts);
            cell?.PutValue(record.Pz);

            cell = null;
            cell = m_worksheet.Cells.Find("_jz", cell, opts);
            cell?.PutValue(record.Jz);

            cell = null;
            cell = m_worksheet.Cells.Find("_mzsby", cell, opts);
            cell?.PutValue(record.Mzsby);

            cell = null;
            cell = m_worksheet.Cells.Find("_pzsby", cell, opts);
            cell?.PutValue(record.Pzsby);

            cell = null;
            cell = m_worksheet.Cells.Find("_mzrq", cell, opts);
            cell?.PutValue(record.Mzrq);

            cell = null;
            cell = m_worksheet.Cells.Find("_pzrq", cell, opts);
            cell?.PutValue(record.Pzrq);

            cell = null;
            cell = m_worksheet.Cells.Find("_jzrq", cell, opts);
            cell?.PutValue(record.Jzrq);

            cell = null;
            cell = m_worksheet.Cells.Find("_kz", cell, opts);
            cell?.PutValue(record.Kz);

            cell = null;
            cell = m_worksheet.Cells.Find("_kl", cell, opts);
            cell?.PutValue(record.Kl);

            cell = null;
            cell = m_worksheet.Cells.Find("_sz", cell, opts);
            cell?.PutValue(record.Sz);

            cell = null;
            cell = m_worksheet.Cells.Find("_bz", cell, opts);
            cell?.PutValue(record.Bz);

            cell = null;
            cell = m_worksheet.Cells.Find("_by1", cell, opts);
            cell?.PutValue(record.By1);

            cell = null;
            cell = m_worksheet.Cells.Find("_by2", cell, opts);
            cell?.PutValue(record.By2);

            cell = null;
            cell = m_worksheet.Cells.Find("_by3", cell, opts);
            cell?.PutValue(record.By3);

            cell = null;
            cell = m_worksheet.Cells.Find("_by4", cell, opts);
            cell?.PutValue(record.By4);

            cell = null;
            cell = m_worksheet.Cells.Find("_by5", cell, opts);
            cell?.PutValue(record.By5);

            cell = null;
            cell = m_worksheet.Cells.Find("_weighName", cell, opts);
            cell?.PutValue(record.WeighName);

            cell = null;
            cell = m_worksheet.Cells.Find("_weigh2Name", cell, opts);
            cell?.PutValue(record.Weigh2Name);
            cell = null;
            cell = m_worksheet.Cells.Find("_dyrq", cell, opts);
            cell?.PutValue(record.Dyrq);


            //2022-05-25新增一下内容 By:汪虎
            cell = null;
            cell = m_worksheet.Cells.Find("_gblx", cell, opts);
            cell?.PutValue(record.Gblx);

            cell = null;
            cell = m_worksheet.Cells.Find("_je", cell, opts);
            cell?.PutValue(record.Je);

            cell = null;
            cell = m_worksheet.Cells.Find("_axleNum", cell, opts);
            cell?.PutValue(record.AxleNum);

            cell = null;
            cell = m_worksheet.Cells.Find("_amount", cell, opts);
            cell?.PutValue(record.Amount);

            cell = null;
            cell = m_worksheet.Cells.Find("_credit", cell, opts);
            cell?.PutValue(record.Credit);

            cell = null;
            cell = m_worksheet.Cells.Find("_weigh", cell, opts);
            cell?.PutValue(record.Weigh);

            cell = null;
            cell = m_worksheet.Cells.Find("_isLimit", cell, opts);
            cell?.PutValue(record.IsLimit ? "是" : "否");

            cell = null;
            cell = m_worksheet.Cells.Find("_isCover", cell, opts);
            cell?.PutValue(record.IsCover.GetValueOrDefault() ? "是" : "否");

            cell = null;
            cell = m_worksheet.Cells.Find("_iccard", cell, opts);
            cell?.PutValue(record.ICCard);

            cell = null;
            cell = m_worksheet.Cells.Find("_isPay", cell, opts);
            cell?.PutValue(record.IsPay == 1 ? "电子支付" : record.IsPay == 2 ? "线下支付" : record.IsPay == 3 ? "储值支付" : record.IsPay == 4 ? "免费放行" : "未支付");


            //新增打印此车当日总车次总毛净重
            cell = ws.Cells.Find("{weighcount}", cell, opts);
            if (cell != null)
            {
                string date = System.DateTime.Now.ToString("yyyy-MM-dd");
                var list = SQLDataAccess.LoadWeighingRecordCount(record.Ch, date);
                decimal mzcount = 0;
                decimal jzcount = 0;
                foreach (var item in list)
                {
                    mzcount += Convert.ToDecimal(item.Mz);
                    jzcount += Convert.ToDecimal(item.Jz);
                }
                cell.Value = $"{date}:车号{record.Ch},总车次{list.Count},总毛重{mzcount},总净重{jzcount}"; ;
            }
            #endregion

            //使用aspose插件将excel转换为图片
            printBitmap = ExcelToBmp(m_worksheet);

            try
            {
                //从数据库中读取配置的自定义纸张大小
                PrintDocument pd = new PrintDocument();
                PaperSize ps = new PaperSize("自定义", iWidth, iHeight);
                pd.DefaultPageSettings.PaperSize = ps;

                pd.PrintPage += new PrintPageEventHandler(Pd_PrintPage);

                //PrintPreviewDialog ppd = new PrintPreviewDialog();
                //ppd.WindowState = FormWindowState.Maximized;
                //ppd.Document = pd;
                //ppd.ShowDialog();                
                if (appSection.Settings["PrintingMode"].Value.Equals("Priview"))
                {
                    PrintPreviewDialog ppd = new PrintPreviewDialog();
                    ppd.WindowState = FormWindowState.Maximized;
                    ppd.Document = pd;
                    ppd.ShowDialog();
                }
                else
                {
                    string[] pList = appSection.Settings["Printer"].Value.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var p in pList)
                    {
                        pd.PrinterSettings.PrinterName = p;
                        pd.Print();
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        //打印eventhandler
        private static void Pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            ev.Graphics.DrawImage(printBitmap, 0, 0);
            ev.HasMorePages = false;
        }

        //使用aspose插件将excel转换为图片
        private static Bitmap ExcelToBmp(Worksheet m_worksheet)
        {
            ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
            imgOptions.OnePagePerSheet = true;
            SheetRender sr = new SheetRender(m_worksheet, imgOptions);
            Bitmap bitmap = sr.ToImage(0);

            //int actualImgWidth = bitmap.Size.Width - 40;
            //int actualImgHeight = bitmap.Size.Height - 40;
            //Bitmap printBitmap = new Bitmap(actualImgWidth, actualImgHeight);

            Graphics graphic = Graphics.FromImage(bitmap);
            //graphic.DrawImage(bitmap, 0, 0, new Rectangle(20, 20, actualImgWidth, actualImgHeight), GraphicsUnit.Pixel);
            //2023/09/4 阿缪删除了补充打印文字
            graphic.DrawString("", new System.Drawing.Font("宋体", 12), new SolidBrush(Color.Black), new PointF(40, 20));

            return bitmap;
        }

    }
}
